import os
import json
import pdfkit
from flask import Blueprint, render_template, \
    current_app, request, flash, redirect, url_for, jsonify
from flask_login import login_required
from flask.helpers import send_file
from app.models.article import Article
from app.models.report import Report
from app.forms.report import ReportForm
from app.extensions import db
from app.helpers import generate_pdf_name
from app.decorators import permission_required

bp = Blueprint('report', __name__)


@bp.before_request
@login_required
def before_request():
    pass


@bp.route('/')
@permission_required('REPORT_INDEX')
def index():
    page = request.args.get('page', 1, type=int)
    pre_page = current_app.config['POST_PRE_PAGE']
    pagination = Report.query.order_by(Report.id.desc()).paginate(
        page, pre_page)
    return render_template('admin/report/index.html',
                           model=pagination.items,
                           page=page,
                           pagination=pagination)


@bp.route('/delete/<int:id>')
@permission_required('REPORT_DELETE')
def delete(id):
    model = Report.query.get_or_404(id)
    with db.auto_commit():
        for aitem in model.articles:
            model.articles.remove(aitem)
        db.session.delete(model)
        model.file_url and os.remove(
            os.path.join(current_app.config.get('PDF_UPLOAD_PATH'),
                         model.file_url))
    flash('删除成功', 'success')
    return redirect(request.referrer or url_for('report.index'))


@bp.route('/download/<int:id>')
@permission_required('REPORT_DOWNLOAD')
def download_report(id):
    report = Report.query.get_or_404(id)
    # if report.status != 8:
    #     flash('下载失败，需要领导审核通过后，方能下载', 'danger')
    #     return redirect(request.referrer or url_for('report.index'))

    file_url = generate_pdf_name()
    report.file_url = file_url
    pdfkit.from_url(
        'http://127.0.0.1:5000' + url_for('site.report_preview', id=id),
        os.path.join(current_app.config['PDF_UPLOAD_PATH'], report.file_url))
    db.session.commit()

    # if report.file_url is None:
    #     file_url = generate_pdf_name()
    #     report.file_url = file_url
    #     pdfkit.from_url(
    #         'http://127.0.0.1:5000' + url_for('site.report_preview', id=id),
    #         os.path.join(current_app.config['PDF_UPLOAD_PATH'], report.file_url))
    #     db.session.commit()

    pdf_url = os.path.join(current_app.config['PDF_UPLOAD_PATH'],
                           report.file_url)
    return send_file(pdf_url, as_attachment=True)


@bp.route('/ajax_report', methods=['POST'])
@permission_required('REPORT_SUBMIT')
def ajax_report():
    form = ReportForm()
    if form.validate_on_submit():
        items = json.loads(form.items.data)
        articles = Article.query.filter(
            Article.id.in_([i['id'] for i in items]),
            Article.audit_status == 7).all()

        try:
            for item in articles:
                item.sort = [
                    int(i['sort']) for i in items if int(i['id']) == item.id
                ][0]
        except IndexError:
            return jsonify({'success': False, 'message': '数据异常，请联系管理员'})

        report = Report(title=form.title.data,
                        sub_title=form.sub_title.data,
                        report_person=form.report_person.data,
                        push_person=form.push_person.data,
                        edit_person=form.edit_person.data,
                        sign_issue=form.sign_issue.data,
                        num=form.num.data)
        for article in articles:
            report.articles.append(article)
        db.session.add(report)
        db.session.commit()
        flash('专报推送成功', 'success')
        return jsonify({'success': True, 'message': '添加成功'})

    if form.errors:
        message = {i[0]: i[1][0] for i in form.errors.items()},
        flash('专报生成失败, 请联系管理员!{}'.format(message), 'danger')
        return jsonify(success=False, message=message)
